<template>
  <div class="margin-container-list">
    <!-- tab区 -->
    <div class="tab-style-default">
      <el-tabs v-model="tabActive" @tab-click="doChangeTab">
        <el-tab-pane :label="labels[1]" name="1"> </el-tab-pane>
        <el-tab-pane :label="labels[2]" name="2"> </el-tab-pane>
        <el-tab-pane :label="labels[4]" name="4"> </el-tab-pane>
        <el-tab-pane :label="labels[-1]" name="-1"> </el-tab-pane>
        <el-tab-pane :label="labels['all']" name="all"> </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 条件区 -->
    <div class="mar-b-20">
      <div class="inline-flex">
        <el-select v-model="textCol" style="width: 150px">
          <el-option label="采购申请单号" value="purchaseOrderNo"></el-option>
        </el-select>
        <el-input v-model="textValue" placeholder="请输入内容" style="width: 200px;"></el-input>
      </div>
      <el-select v-model="defaultQuery.warehouseId" placeholder="仓库" clearable class="pad-l-10">
        <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.warehouseName"
          :value="item.warehouseId"></el-option>
      </el-select>
      <el-select v-model="defaultQuery.purchaseOrderStatus" v-if="purchaseOrderStatusList.length > 0" placeholder="状态"
        clearable class="pad-l-10" style="width: 140px">
        <template v-for="(item, index) in purchaseOrderStatusList">
          <el-option v-if="item.value != '0'" :key="index" :label="item.label" :value="item.value"></el-option>
        </template>
      </el-select>
      <div class="inline-flex">
        <el-select v-model="dateTimeValue" class="pad-l-10" style="width: 120px">
          <el-option label="创建时间" value="createTime"></el-option>
          <el-option label="提交时间" value="submitTime"></el-option>
          <el-option label="审核时间" value="auditTime"></el-option>
          <el-option label="完成时间" value="completeTime"></el-option>
        </el-select>
        <el-date-picker v-model="dateTimePicker" type="datetimerange" range-separator="至"
          value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <el-button-group class="mar-l-20">
        <el-button type="primary" @click="doSearch">查询</el-button>
        <el-button plain @click="doResetSearch">重置</el-button>
      </el-button-group>
    </div>
    <!-- 按钮区 -->
    <div class="mar-b-20 btn-area">
      <el-button type="primary" v-if="tabActive == '1'" @click="doSetInvoiceType('')">批量设置发票类型</el-button>
      <el-button type="primary" v-if="tabActive == '1'" @click="doBatchAuditOrder">批量审核</el-button>
      <el-button @click="doExport">导出</el-button>
    </div>
    <!-- 内容列表 -->
    <div class="table-container">
      <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
        element-loading-text="加载中">
        <el-table-column width="50px" type="selection"></el-table-column>
        <el-table-column min-width="280px" label="采购申请单号" prop="purchaseOrderNo" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.purchaseOrderNo }}</span>
            <br />
            <span class="font-blue">（{{ scope.row.warehouseName }}）</span>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" label="商品总数量" prop="goodsNum" align="center">
        </el-table-column>
        <el-table-column min-width="150px" label="总金额" prop="purchaseOrderAmount" align="center">
          <template slot-scope="scope">
            <span>￥{{ scope.row.purchaseOrderAmount }}</span>
          </template>
        </el-table-column>
        <!-- 【入库中】【已完成】【全部】下显示此列 -->
        <el-table-column v-if="tabActive == '2' || tabActive == '4' || tabActive == 'all'" width="220px" label="入库/退货数量"
          align="center">
          <template slot-scope="scope">
            <span>已入库：{{ scope.row.stockInNum }}</span>
            <br />
            <span class="font-red" v-if="scope.row.stockOutNum > 0">已退货：{{ scope.row.stockOutNum }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" label="发票类型" prop="invoiceType" align="center">
          <template slot-scope="scope">
            <span>{{ dict.invoiceType[scope.row.invoiceType] }}</span>
          </template>
        </el-table-column>
        <!-- 【入库中】【已完成】【全部】下显示此列 -->
        <el-table-column v-if="tabActive == '2' || tabActive == '4' || tabActive == 'all'" width="220px" label="状态"
          align="center">
          <template slot-scope="scope">
            <span>{{ dict.purchaseOrderStatus[scope.row.purchaseOrderStatus] }}</span>
          </template>
        </el-table-column>
        <!-- 【审核未通过】下显示此列 -->
        <el-table-column v-if="tabActive == '-1'" width="220px" label="审核意见" prop="auditRemark" align="center">
          <template slot-scope="scope">
            <el-popover placement="top" width="200" trigger="click" :content="scope.row.auditRemark">
              <el-button type="text" slot="reference">点击查看</el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column width="280px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="doLinkDetail(scope.row)">查看详情</el-button>
            <el-button type="text" size="medium" v-if="scope.row.purchaseOrderStatus == 1"
              @click="doSetInvoiceType(scope.row)">设置发票类型</el-button>
            <el-button type="text" size="medium" v-if="scope.row.purchaseOrderStatus == 1"
              @click="doAuditOrder(scope.row)">审核</el-button>
            <el-button type="text" size="medium"
              v-if="scope.row.purchaseOrderStatus == 2 || scope.row.purchaseOrderStatus == 3"
              @click="doStopOrder(scope.row)">终止</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 设置发票类型dialog -->
    <el-dialog title="设置发票类型" :visible.sync="invoiceTypeVisible" width="450px">
      <el-form ref="invoiceTypeForm" :model="invoiceTypeForm" label-width="160px" style="width: 410px">
        <el-form-item label="进项发票类型：">
          <el-select v-model="invoiceTypeForm.invoiceType">
            <el-option v-for="(item, key) in dict.invoiceType" :key="key" :label="item" :value="key"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doSaveInvoiceType">保存</el-button>
        <el-button @click="invoiceTypeVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 采购单审核dialog -->
    <el-dialog width="500px" title="采购单审核" :visible.sync="auditVisible">
      <div v-loading="listLoading">
        <el-form ref="auditForm" :model="auditForm" label-width="120px" style="width: 460px">
          <el-form-item label="审核结果：" prop="purchaseOrderStatus">
            <el-radio-group v-model="auditForm.purchaseOrderStatus">
              <el-radio :label="2">审核通过</el-radio>
              <el-radio :label="-1">审核不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见：">
            <el-input type="textarea" :rows="3" v-model="auditForm.auditRemark"></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer mar-b-10">
          <el-button type="primary" @click="doSaveAudit">确定</el-button>
          <el-button @click="auditVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    listWarehouseInfo
  } from '@/api/warehouse/warehouseInfo'
  import {
    pagingPurchaseOrder,
    statPurchaseOrder,
    doExportByEnterprise,
    saveInvoiceType,
    doAudit,
    batchAudit,
    updateBatchPurchaseOrderStatusByIds
  } from '@/api/warehouse/purchaseOrder'

  export default {
    data() {
      return {
        // tab选中对象
        tabActive: '1',
        // tab标签
        labels: {
          '1': '待审核(0)',
          '2': '出库中(0)',
          '4': '已完成(0)',
          '-1': '审核未通过(0)',
          'all': '全部采购申请(0)'
        },
        // tab标签模板
        labelTemp: {
          '1': '待审核(s)',
          '2': '出库中(s)',
          '4': '已完成(s)',
          '-1': '审核未通过(s)',
          'all': '全部采购申请(s)'
        },
        // 数据字典
        dict: {
          purchaseOrderStatus: {},
          invoiceType: {}
        },
        // 文本model
        textCol: 'purchaseOrderNo',
        textValue: '',
        // 日期model
        dateTimeValue: 'createTime',
        dateTimePicker: [],
        // 默认条件
        defaultQuery: {
          enterpriseId: '',
          currentPage: 1,
          size: 10,
          warehouseId: '',
          purchaseOrderStatus: ''
        },
        // 查询条件
        searchListQuery: {},
        // 采购单状态集合
        purchaseOrderStatusList: [],
        // 采购单审核表单
        auditForm: {
          purchaseOrderId: '',
          purchaseOrderIds: [],
          purchaseOrderStatus: 2,
          zeroPriceFlag: 0,
          auditRemark: ''
        },
        // 进项发票表单
        invoiceTypeForm: {
          invoiceType: '',
          purchaseOrderIds: []
        },
        // 进项发票visible
        invoiceTypeVisible: false,
        // 采购单审核visible
        auditVisible: false,
        // 仓库集合
        warehouseList: [],
        // 勾选集合
        multipleSelection: [],
        total: 0,
        listLoading: false,
        dataList: []
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      // 获取仓库列表
      const form = {
        enterpriseId: this.getEnterpriseId(),
        supplierId: this.getSupplierId(),
        warehouseSource: this.getSupplierId() ? 2 : 1
      }
      listWarehouseInfo(form).then((response) => {
        this.warehouseList = response.data
      })
      // 获取数据字典
      getDictByGroupName('InvoiceApplyDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      this.stat()
      this.initList()
    },
    methods: {
      // tab切换事件
      doChangeTab() {
        var list = []
        if (this.tabActive === '2' || this.tabActive === '4' || this.tabActive === 'all') {
          for (var key in this.dict.purchaseOrderStatus) {
            if (this.dict.purchaseOrderStatus[key] === '待入库') {
              this.dict.purchaseOrderStatus[key] = '待出库'
            }
            if (this.dict.purchaseOrderStatus[key] === '部分入库') {
              this.dict.purchaseOrderStatus[key] = '部分出库'
            }
            list.push({
              label: this.dict.purchaseOrderStatus[key],
              value: key
            })
          }
          // 显示状态【已完成】【已终止】
          if (this.tabActive === '2') {
            list = list.filter(item => item.value === '2' || item.value === '3')
          }
          // 显示状态【已完成】【已终止】
          if (this.tabActive === '4') {
            list = list.filter(item => item.value === '4' || item.value === '-2')
          }
          // 除了【待提交】以外
          if (this.tabActive === 'all') {
            list = list.filter(item => item.value !== '0')
          }
        }
        this.purchaseOrderStatusList = list
        this.stat()
        this.doResetSearch()
      },
      initList() {
        this.setQueryCondition()
        this.listLoading = true
        pagingPurchaseOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          this.dataList = response.data.records
          this.total = response.data.total
          Object.assign(this.dict, response.data.dict)
          for (var key in this.dict.purchaseOrderStatus) {
            if (this.dict.purchaseOrderStatus[key] === '待入库') {
              this.dict.purchaseOrderStatus[key] = '待出库'
            }
            if (this.dict.purchaseOrderStatus[key] === '部分入库') {
              this.dict.purchaseOrderStatus[key] = '部分出库'
            }
          }
        })
      },
      // 设置查询条件
      setQueryCondition() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.dateColumn = this.dateTimeValue
        this.searchListQuery.purchaseOrderType = 2
        this.searchListQuery.startDate = (this.dateTimePicker && this.dateTimePicker.length > 0) ? this.dateTimePicker[
          0] : ''
        this.searchListQuery.endDate = (this.dateTimePicker && this.dateTimePicker.length > 1) ? this.dateTimePicker[
          1] : ''
        if (!this.searchListQuery.purchaseOrderStatus) {
          let tabStatus = ''
          switch (this.tabActive) {
            case '1':
            case '-1':
              tabStatus = this.tabActive
              break
            case '2':
            case '4':
            case 'all':
              tabStatus = this.purchaseOrderStatusList.map(item => item.value).join(',')
              break
            default:
          }
          this.searchListQuery.purchaseOrderStatusList = tabStatus
        }
      },
      // 统计
      stat() {
        statPurchaseOrder({
          enterpriseId: this.getEnterpriseId(),
          purchaseOrderType: 2
        }).then(response => {
          if (response.isError) return
          this.labels[1] = this.labelTemp[1].replace('s', response.data[1])
          this.labels[2] = this.labelTemp[2].replace('s', response.data[2] + response.data[3])
          this.labels[4] = this.labelTemp[4].replace('s', response.data[4] + response.data[-2])
          this.labels[-1] = this.labelTemp[-1].replace('s', response.data[-1])
          this.labels['all'] = this.labelTemp['all'].replace('s', response.data['all'])
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.dateTimeValue = originData.dateTimeValue
        this.dateTimePicker = originData.dateTimePicker
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 导出事件
      doExport() {
        if (this.dataList.length === 0) {
          this.$message({
            type: 'error',
            message: '暂无可导出数据'
          })
          return
        }
        let form = {
          enterpriseId: this.getEnterpriseId()
        }
        if (this.multipleSelection.length > 0) {
          const purchaseOrderIds = this.multipleSelection.map(item => item.purchaseOrderId)
          form.purchaseOrderIds = purchaseOrderIds.join(',')
          form.purchaseOrderStatusList = this.searchListQuery.purchaseOrderStatusList
        } else {
          this.setQueryCondition()
          form = this.searchListQuery
        }
        window.open(doExportByEnterprise(form), '_blank')
      },
      // 查看详情
      doLinkDetail(row) {
        this.$router.push({
          path: '/warehouse/warehouse-refund-goods-manage/detail/index',
          query: {
            purchaseOrderId: row.purchaseOrderId
          }
        })
      },
      // 设置发票类型事件
      doSetInvoiceType(row) {
        if (row) {
          this.invoiceTypeForm = {
            invoiceType: row.invoiceType.toString(),
            purchaseOrderIds: row.purchaseOrderId.split('-')
          }
        } else {
          if (this.multipleSelection.length === 0) {
            this.$message({
              type: 'error',
              message: '请选择采购单'
            })
            return
          }
          this.invoiceTypeForm = {
            invoiceType: '0',
            purchaseOrderIds: this.multipleSelection.map(item => item.purchaseOrderId)
          }
        }
        this.invoiceTypeVisible = true
      },
      // 保存发票类型事件
      doSaveInvoiceType() {
        saveInvoiceType(this.invoiceTypeForm).then(response => {
          if (response.isError) return
          this.invoiceTypeVisible = false
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.initList()
        })
      },
      // 采购单审核打开事件
      doAuditOrder(row) {
        const originData = this.$options.data()
        this.auditForm = originData.auditForm
        this.auditForm.purchaseOrderId = row.purchaseOrderId
        this.auditForm.zeroPriceFlag = row.zeroPriceFlag
        this.auditVisible = true
      },
      // 采购单审核确定事件
      doSaveAudit() {
        if (this.auditForm.zeroPriceFlag === 1 && this.auditForm.purchaseOrderStatus === 2) {
          this.$confirm('采购单中含有单价为0的商品，是否继续审核？', '提示', {
            confirmButtonText: '继续审核',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveAudit()
          }).catch(() => {})
        } else {
          this.saveAudit()
        }
      },
      // 审核处理
      saveAudit() {
        this.listLoading = true
        if (this.auditForm.purchaseOrderIds.length > 0) {
          batchAudit(this.auditForm).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.auditVisible = false
            const data = response.data
            const msg = '共审核' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
            this.$message({
              type: 'success',
              message: msg
            })
            this.stat()
            this.initList()
          })
        } else {
          doAudit(this.auditForm).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.auditVisible = false
            this.$message({
              type: 'success',
              message: '审核成功'
            })
            this.stat()
            this.initList()
          })
        }
      },
      // 批量审核事件
      doBatchAuditOrder() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择采购单'
          })
          return
        }
        const purchaseOrderIds = this.multipleSelection.map(item => item.purchaseOrderId)
        const zeroPriceFlags = this.multipleSelection.map(item => item.zeroPriceFlag)
        const originData = this.$options.data()
        this.auditForm = originData.auditForm
        this.auditForm.purchaseOrderIds = purchaseOrderIds
        this.auditForm.zeroPriceFlag = zeroPriceFlags.indexOf(1) !== -1 ? 1 : 0
        this.auditVisible = true
      },
      // 终止事件
      doStopOrder(row) {
        var totalWaitWarehouseOutNum = row.totalWaitWarehouseOutNum
        var notWarehouseOutNum = row.notWarehouseOutNum
        if (totalWaitWarehouseOutNum > 0) {
          this.$message({
            type: 'error',
            message: '采购退货申请存在未确认的出库数量，不允许终止!'
          })
          return
        }
        var tips = '确定要终止采购单吗?'
        if (notWarehouseOutNum > 0) {
          tips = '采购退货申请还有' + notWarehouseOutNum + '件商品未出库，终止后将不能再继续出库，确定要终止当前采购退货申请？'
        }
        this.$confirm(tips, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var purchaseOrderIds = []
          purchaseOrderIds.push(row.purchaseOrderId)
          updateBatchPurchaseOrderStatusByIds(purchaseOrderIds, -2, '手动终止').then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '终止成功'
            })
            this.initList()
          })
        }).catch(() => {})
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .btn-area {
    button {
      min-width: 90px;
    }
  }
</style>
